<?php
include_once('inc/functions.inc.php');

if (!isEmpty(getParam('operation'))) {

    switch (getParam('operation')) {
        case 'filtro': {
                fntAcademicoCobrosAnulacionFiltro($db);
                break;
            }
        case 'secciones': {
                fntAcademicoCobrosAnulacionFiltroSecciones($db);
                break;
            }
        case 'contenido': {
                fntAcademicoCobrosAnulacionContenido($db);
                break;
            }
        case 'contenidoDetalle': {
                fntAcademicoCobrosAnulacionContenidoDetalle($db);
                break;
            }
        case 's': {
                fntAcademicoCobrosAnulacionGrabar($db);
                break;
            }
    }
    die();
}

function fntAcademicoCobrosAnulacionFiltro($db) {
    $strQuery = "";
    $strSelected = "";
    ?>
    <div style="width: 1000px; height: 30px; float: left;">&nbsp;</div>
    <div style="width: 200px; height: 30px; float: left;"><b>Estudiante / Benefactor</b></div>
    <div style="width: 800px; height: 30px; float: left;">
        <select title="fntAcademicoCobrosAnulacionContenido" 
                name="txtAcademicoCobrosAnulacion_FK-ESTUDIANTE" id="txtAcademicoCobrosAnulacion_FK-ESTUDIANTE">
            <option value=""></option>
            <?php
            $strQuery = "SELECT  cllg_student.ID, cllg_student.FIRST_NAME, cllg_student.LAST_NAME, 
                                cllg_academico_cobros.ID AS COBRO
                        FROM    cllg_academico_cobros,
                                cllg_student 
                        WHERE   cllg_academico_cobros.FK_ESTUDIANTE = cllg_student.ID 
                        AND     cllg_academico_cobros.TIPO = 'ESTUDIANTE' 
                        AND     cllg_academico_cobros.ESTADO in ('PAGADO','PAGADOPARCIAL')
                        AND cllg_academico_cobros.ID 
                            in( SELECT cllg_academico_pagos_detail.FK_COBRO_ID
                                FROM cllg_academico_pagos_detail, cllg_academico_pagos
                                    WHERE cllg_academico_pagos.ESTADO = 'CERRADO'
                                    AND cllg_academico_pagos.ID = cllg_academico_pagos_detail.FK_PAGO_ID )
                        GROUP   BY cllg_student.ID";
            $qTMP = $db->queryToArray($strQuery, true);
            ea_htmlentities($qTMP);
            foreach ($qTMP as $rTMP) {
                ?>
                <option value="<?php print $rTMP["ID"] . "_ESTUDIANTE"; ?>" 
                        <?php print $strSelected; ?>><?php print $rTMP["ID"] . " - " . $rTMP["FIRST_NAME"] . " " . $rTMP["LAST_NAME"]; ?></option>                <?php
            }
            $strQuery = "SELECT cllg_benefactor.ID, cllg_benefactor.RAZON_SOCIAL,  
                                cllg_academico_cobros.ID AS COBRO 
                        FROM    cllg_academico_cobros,
                                cllg_benefactor 
                        WHERE   cllg_academico_cobros.FK_ESTUDIANTE = cllg_benefactor.ID 
                        AND     cllg_academico_cobros.TIPO = 'BENEFACTOR' 
                        AND     cllg_academico_cobros.ESTADO in ('PAGADO','PAGADOPARCIAL')
                        AND cllg_academico_cobros.ID 
                            in( SELECT cllg_academico_pagos_detail.FK_COBRO_ID
                                FROM cllg_academico_pagos_detail, cllg_academico_pagos
                                    WHERE cllg_academico_pagos.ESTADO = 'CERRADO'
                                    AND cllg_academico_pagos.ID = cllg_academico_pagos_detail.FK_PAGO_ID )
                        GROUP   BY cllg_benefactor.ID";
            $qTMP = $db->queryToArray($strQuery, true);
            ea_htmlentities($qTMP);
            foreach ($qTMP as $rTMP) {
                        ?>
                <option value="<?php print $rTMP["ID"] . "_BENEFACTOR"; ?>" 
                        <?php print $strSelected; ?>><?php print $rTMP["ID"] . " - " . $rTMP["RAZON_SOCIAL"]; ?></option>
                    <?php } ?>
        </select>
    </div>
    <div style="width: 500px; float: left; text-align: center;">&nbsp;</div>
    <style>
        .ui-button { margin-left: -1px; }
        .ui-button-icon-only .ui-button-text { padding: 0.01em; } 
        .ui-autocomplete-input { margin: 0; padding: 0.0em 0 0.0em 0.0em; }
    </style>
    <script language="javascript" type="text/javascript">
        $(function() {
            $("#txtAcademicoCobrosAnulacion_FK-ESTUDIANTE").combobox(fntAcademicoCobrosAnulacionContenido);
        });    
    </script>    
    <script type="text/javascript">
        $(function() {
            $("[name='txtAcademicoCobrosAnulacion_FK-ESTUDIANTE']").change( function() {
                fntAcademicoCobrosAnulacionContenido();
            });
        });
    </script>
    <?php
}

function fntAcademicoCobrosAnulacionContenido($db) {

    $strEstudianteBenefactor = isset($_POST["txtAcademicoCobrosAnulacion_FK-ESTUDIANTE"]) ? $_POST["txtAcademicoCobrosAnulacion_FK-ESTUDIANTE"] : "";
    $arrEstudianteBenefactor = explode("_", $strEstudianteBenefactor);
    $intID = $arrEstudianteBenefactor[0];
    $strTipo = $arrEstudianteBenefactor[1];

    $arrMes = array();
    $arrMes[1] = "Enero";
    $arrMes[2] = "Febrero";
    $arrMes[3] = "Marzo";
    $arrMes[4] = "Abril";
    $arrMes[5] = "Mayo";
    $arrMes[6] = "Junio";
    $arrMes[7] = "Julio";
    $arrMes[8] = "Agosto";
    $arrMes[9] = "Septiembre";
    $arrMes[10] = "Octubre";
    $arrMes[11] = "Noviembre";
    $arrMes[12] = "Diciembre";
    ?>
    <br>
    <?php
    if ($strTipo == "ESTUDIANTE") {
        ?>
        <div id="divContenidoEstudianteDetalle" style=" margin-bottom: 5px; padding: 5px; width: 800px; float: left;" class="ui-widget-content ui-corner-all">
            <?php
            $arrInfo = array();
            $strQuery = "SELECT  EA.*, 
                                G.NOMBRE AS GRADO, 
                                S.NOMBRE AS SECCION
                        FROM    cllg_academico_estudiantes_asignacion AS EA,
                                cllg_academico_grados AS G,
                                cllg_academico_secciones AS S
                        WHERE   EA.FK_GRADO = G.ID
                        AND     EA.FK_SECCION = S.ID
                        AND     EA.FK_ESTUDIANTE = '{$intID}'";
            $qTMP = $db->query($strQuery);
            while ($rTMP = $db->fetch_array($qTMP)) {
                $arrInfo = $rTMP;
            }
            $db->free_result($qTMP);
            ?>
            <div style="width: 100px; float: left;"><b>Grado</b></div>
            <div style="width: 900px; float: left;">&nbsp;<?php print $arrInfo["GRADO"]; ?></div>
            <div style="width: 100px; float: left;"><b>Sección</b></div>
            <div style="width: 900px; float: left;">&nbsp;<?php print $arrInfo["SECCION"]; ?></div>
            <?php
            $arrInfo = array();
            $strQuery = "SELECT  P.*  
                        FROM    cllg_student AS E,
                                cllg_parent AS P,
                                cllg_student_parent AS EP
                        WHERE   E.ID = EP.STUDENT
                        AND     P.ID = EP.PARENT
                        AND     E.ID = '{$intID}'";
            $arrInfo = array("NOMBRE_A" => "", "APELLIDO_A" => "");
            $qTMP = $db->queryToArray($strQuery, true);
            foreach ($qTMP as $rTMP) {
                $arrInfo = $rTMP;
            }
            $db->free_result($qTMP);
            ?>
            <div style="width: 100px; float: left;"><b>Padre</b></div>
            <div style="width: 900px; float: left;">&nbsp;<?php print $arrInfo["NOMBRE_A"] . " " . $arrInfo["APELLIDO_A"]; ?></div>    
            <?php
            $arrInfo = array();
            $strQuery = "SELECT  B.*  
                        FROM    cllg_student AS E,
                                cllg_benefactor AS B,
                                cllg_student_benefactor AS EB
                        WHERE   E.ID = EB.STUDENT
                        AND     B.ID = EB.BENEFACTOR
                        AND     E.ID = '{$intID}'";
            $qTMP = $db->queryToArray($strQuery, true);
            foreach ($qTMP as $rTMP) {
                $arrInfo = $rTMP;
            }
            $db->free_result($qTMP);
            ?>
            <div style="width: 100px; float: left;"><b>Benefactor</b></div>
            <div style="width: 900px; float: left;">&nbsp;<?php print $arrInfo["RAZON_SOCIAL"]; ?></div>    
        </div>
        <?php
    }
    if ($strTipo == "BENEFACTOR") {
        ?>
        <div style="width: 300px; float: left; margin-right: 5px; padding: 5px;" class="ui-widget-content ui-corner-all">
            <h3>Estudiantes</h3>
            <div style="width: 100%; float: left;">
                <ul>
                    <?php
                    $strQuery = "SELECT  E.*  
                    FROM    cllg_student AS E,
                            cllg_student_benefactor AS EB
                    WHERE   E.ID = EB.STUDENT
                    AND     EB.BENEFACTOR = '{$intID}'";
                    $qTMP = $db->query($strQuery);
                    while ($rTMP = $db->fetch_array($qTMP)) {
                        ?>
                        <li><?php print $rTMP["FIRST_NAME"] . " " . $rTMP["LAST_NAME"]; ?></li>                
                    <?php }
                    ?>
                </ul>
            </div>
            <?php
            $db->free_result($qTMP);
        }
        /* $strQuery ="SELECT  cllg_academico_cobros.ID, 
          MONTH(cllg_academico_cobros.FECHA) AS MES, cllg_academico_cobros.VALOR, cllg_academico_cargos_detail.VIGENCIA
          FROM    cllg_academico_cobros,
          cllg_academico_cargos_detail
          WHERE   cllg_academico_cobros.FK_CARGO_DETAIL_ID = cllg_academico_cargos_detail.ID
          AND     cllg_academico_cobros.FK_ESTUDIANTE = '{$intID}'
          AND     cllg_academico_cobros.TIPO = '{$strTipo}'
          AND     cllg_academico_cargos_detail.TIPO = '{$strCargoTipo}'
          AND     cllg_academico_cobros.ESTADO IN ('PAGADO','PAGADOPARCIAL') "; */
        ?>
    </div>
    <div style=" padding: 5px; width: 800px; float: left; " class="ui-widget-content ui-corner-all">
        <input type="hidden" id="hdnFkCtaCorriente" name="hdnFkCtaCorriente" value="<?php echo $intID . "_" . $strTipo; ?>" />
        <table width="80%" cellpadding="2" cellspacing="2" border="0" style="border-collapse: collapse;">
            <tr>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Codigo de Generación</b></td>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Tipo Cargo</b></td>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Mes</b></td>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Codigo Cobro</b></td>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Valor Cobro</b></td>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Saldo Cobro</b></td>
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;"><b>Valor Abono</b></td>        
                <td width="20%" align="center" style="border: 1px solid black; background-color: #DDDDDD;">&nbsp;</td>
            </tr>
            <?php
            $strCargoTipo = $strTipo;
            $strQuery = "SELECT  
                cllg_academico_cobros.CODIGO, 
                cllg_academico_cobros.ID, 
                MONTH(cllg_academico_cobros.FECHA) AS MES, 
                cllg_academico_cargos_detail.VIGENCIA,
                cllg_academico_cobros.VALOR VALOROCOBRO,
                cllg_academico_pagos_detail.ID IDABONO,
                cllg_academico_cobros.SALDO_ACT SALDOCOBRO, 
                cllg_academico_pagos_detail.FK_PAGO_ID LOTEABONOS,
                cllg_academico_pagos_detail.ID IDABONO,
                cllg_academico_pagos_detail.MONTO VALORABONO
                FROM    cllg_academico_cobros,
                        cllg_academico_cargos_detail,
                        cllg_academico_pagos_detail,
                        cllg_academico_pagos
                WHERE   cllg_academico_cobros.FK_CARGO_DETAIL_ID = cllg_academico_cargos_detail.ID
                AND     cllg_academico_pagos.ESTADO='CERRADO'
            AND     cllg_academico_pagos.ID=cllg_academico_pagos_detail.FK_PAGO_ID
                AND     cllg_academico_pagos_detail.FK_COBRO_ID =  cllg_academico_cobros.ID
                AND     cllg_academico_pagos_detail.ESTADO='VIGENTE'
                AND     cllg_academico_cobros.ESTADO IN ('PAGADO','PAGADOPARCIAL')
                AND     cllg_academico_cobros.TIPO = '{$strCargoTipo}'
                AND     cllg_academico_cobros.FK_ESTUDIANTE = {$intID}
             order by cllg_academico_cobros.ID asc  ";
            $qTMP = $db->query($strQuery);
            while ($rTMP = $db->fetch_array($qTMP)) {
                ?>
                <tr>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $rTMP["CODIGO"]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $rTMP["VIGENCIA"]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $arrMes[$rTMP["MES"]]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $rTMP["ID"]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $rTMP["VALOROCOBRO"]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $rTMP["SALDOCOBRO"]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <?php print $rTMP["VALORABONO"]; ?>
                    </td>
                    <td align="center" style="border: 1px solid black;">
                        <input type="radio" name="radCobroID" value="<?php print $rTMP["IDABONO"]; ?>" />
                    </td>
                </tr>
                <?php
            }
            $db->free_result($qTMP);
            ?>
        </table>
        <div id="divAcademicoCobrosAnulacionContenidoDetalle" style="width: 400px; float: left;">&nbsp;</div>
        <script type="text/javascript" language="javascript">
            $(function() {
                $("[name='radCobroID']").change( function() {
                    fntAcademicoCobrosAnulacionContenidoDetalle();
                });
            });
        </script>
    </div>

    <?php
}

function fntAcademicoCobrosAnulacionContenidoDetalle($db) {

    $intEmpresa = 1;
    $intCobro = isset($_POST["radCobroID"]) ? $_POST["radCobroID"] : "";
    $arrInfo = array();
    ?>
    <script type="text/javascript" language="javascript">
        var intEmpresa = 1;
    </script>
    <?php
    $strQuery = "SELECT  cllg_academico_cobros.ID, cllg_academico_cobros.VALOR, 
                        cllg_academico_pagos_detail.MONTO VALORABONO,
                        DATE_FORMAT(cllg_academico_cobros.FECHA, '%d-%m-%Y') AS FECHA,
                        cllg_academico_cargos_detail.DESCRIPCION, 
                        cllg_academico_cargos_detail.CTA_COBRAR, 
                        cllg_academico_cargos_detail.CTA_INGRESOS, 
                        cllg_academico_pagos.FK_NC, 
                        cllg_academico_pagos_detail.ID AS pagoDetailID,
                        cllg_bnc_notas.FK_CUENTA     
                FROM    cllg_academico_cobros,
                        cllg_academico_cargos_detail,
                        cllg_academico_pagos,
                        cllg_academico_pagos_detail,
                        cllg_bnc_notas 
                WHERE      cllg_academico_cobros.FK_CARGO_DETAIL_ID = cllg_academico_cargos_detail.ID
                AND     cllg_academico_cobros.ID = cllg_academico_pagos_detail.FK_COBRO_ID
                AND     cllg_academico_pagos.ID = cllg_academico_pagos_detail.FK_PAGO_ID
                AND     cllg_academico_pagos.FK_NC = cllg_bnc_notas.ID
                AND     cllg_bnc_notas.TIPO = 1 
                and     cllg_academico_pagos_detail.ID={$intCobro}
                GROUP   BY cllg_academico_cobros.ID";
    $qTMP = $db->query($strQuery);
    while ($rTMP = $db->fetch_array($qTMP)) {
        $arrInfo = $rTMP;
    }
    $db->free_result($qTMP);
    if (isset($arrInfo["FK_CUENTA"])) {
        $strQuery = "SELECT  * 
                FROM    cllg_bnc_cuenta
                WHERE   NUMERO  = '{$arrInfo["FK_CUENTA"]}'";
        $qTMP = $db->query($strQuery);
        while ($rTMP = $db->fetch_array($qTMP)) {

            $strQuery1 = "SELECT * 
                     FROM   cllg_contab_cuenta 
                     WHERE  fk_empresa = '{$intEmpresa}'
                     AND    codigo = '{$rTMP["FK_CUENTA_CONTABLE"]}'";
            $qTMP1 = $db->query($strQuery1);
            while ($rTMP1 = $db->fetch_array($qTMP1)) {
                $arrAjuste["H" . $rTMP1["codigo"]]["codigo"] = $rTMP1["codigo"];
                $arrAjuste["H" . $rTMP1["codigo"]]["nombre"] = $rTMP1["nombre"];
                $arrAjuste["H" . $rTMP1["codigo"]]["tipo"] = "h";
                $arrAjuste["H" . $rTMP1["codigo"]]["monto"] = $arrInfo["VALORABONO"];
            }
            $db->free_result($qTMP1);
        }
        $db->free_result($qTMP);

        $strQuery1 = "SELECT * 
                 FROM   cllg_contab_cuenta 
                 WHERE  fk_empresa = '{$intEmpresa}'
                 AND    codigo = '{$arrInfo["CTA_COBRAR"]}'";
        $qTMP1 = $db->query($strQuery1);
        while ($rTMP1 = $db->fetch_array($qTMP1)) {
            $arrAjuste["D" . $rTMP1["codigo"]]["codigo"] = $rTMP1["codigo"];
            $arrAjuste["D" . $rTMP1["codigo"]]["nombre"] = $rTMP1["nombre"];
            $arrAjuste["D" . $rTMP1["codigo"]]["tipo"] = "d";
            $arrAjuste["D" . $rTMP1["codigo"]]["monto"] = $arrInfo["VALORABONO"];
        }
        $db->free_result($qTMP1);
        ?>
        <input type="hidden" name="sltCuenta_<?php print $arrInfo["ID"]; ?>_<?php print $arrInfo["pagoDetailID"]; ?>" value="<?php print $arrInfo["FK_CUENTA"]; ?>" />
        <input type="hidden" name="hdnMonto_<?php print $arrInfo["ID"]; ?>_<?php print $arrInfo["pagoDetailID"]; ?>" value="<?php print $arrInfo["VALORABONO"]; ?>" />

        <div style="width: 800px; float: left;">
            <div style="width: 800px; float: left;">&nbsp;</div>
            <div style="width: 800px; float: left; text-align: center;"><b>Distribución contable</b></div>
            <div style="width: 800px; float: left;">&nbsp;</div>
            <div style="width: 100px; float: left">&nbsp;</div>
            <div style="width: 600px; float: left;">
                <input type="hidden" name="hdnAcademicoCobrosAnulacionFecha" value="<?php print $arrInfo["FECHA"]; ?>" />
                <input type="hidden" name="hdnAcademicoCobrosAnulacionValor" value="<?php print $arrInfo["VALORABONO"]; ?>" />
                <input type="hidden" name="hdnAcademicoCobrosAnulacionMonto" value="<?php print $arrInfo["VALORABONO"]; ?>" />
                <input type="hidden" name="hdnAcademicoCobrosAnulacionConcepto1" value="<?php print $arrInfo["DESCRIPCION"]; ?>" />
                <b>Descripción</b><br />
                <textarea name="hdnAcademicoCobrosAnulacionConcepto" style="width: 100%"><?php print $arrInfo["DESCRIPCION"]; ?></textarea>
            </div>
            <div style="width: 100px; float: left">&nbsp;</div>
            <div style="width: 800px; float: left">&nbsp;</div>
            <div style="width: 800px; height: auto; float: left; text-align: center;">
                <div id="frmPartidas-detalle" style="width: 800px; float: left;">
                    <div style="float: left; width: 400px; height: 30px; border-bottom: 1px solid black;"><b>Cuenta</b></div>
                    <div style="float: left; width: 200px; height: 30px; border-bottom: 1px solid black; text-align: center;"><b>Debe</b></div>
                    <div style="float: left; width: 200px; height: 30px; border-bottom: 1px solid black; text-align: center;"><b>Haber</b></div>
                    <div style="float: left; width: 400px; height: 10px;">&nbsp;</div>
                    <div style="float: left; width: 200px; height: 10px;">&nbsp;</div>
                    <div style="float: left; width: 200px; height: 10px;">&nbsp;</div>
                </div>
                <div id="frmPartidas-totales" style="width: 800px; float: left;">
                    <div style="float: left; width: 400px; height: 10px; border-collapse: separate; border-bottom: 1px solid black;">&nbsp;</div>
                    <div style="float: left; width: 200px; height: 10px; border-collapse: separate; border-bottom: 1px solid black;">&nbsp;</div>
                    <div style="float: left; width: 200px; height: 10px; border-collapse: separate; border-bottom: 1px solid black;">&nbsp;</div>
                    <div style="float: left; width: 400px; height: 30px; margin-top: 5px; text-align: right;"><b>Totales</b></div>
                    <div style="float: left; width: 200px; height: 30px; margin-top: 5px;"><input type="text" name="txtTotalDebe" id="txtTotalDebe" value="" style="text-align: right;" readonly="readonly"></div>
                    <div style="float: left; width: 200px; height: 30px; margin-top: 5px;"><input type="text" name="txtTotalHaber" id="txtTotalHaber" value="" style="text-align: right;" readonly="readonly"></div>
                </div>
            </div>
            <div style="width: 800px; height: 40px; float: left; text-align: center;">
                &nbsp;
            </div>
            <div style="width: 800px; height: 40px; float: left; text-align: center;">
                <button type="button" id="btnAcademicoCobrosAnulacionGrabar">Grabar</button>
            </div>
            <script type="text/javascript">
                $( function() {
                                    
                    $("#btnAcademicoCobrosAnulacionGrabar").button({
                        icons: {
                            primary: "ui-icon-disk"
                        }
                    }).click( function () {
                        fntAcademicoCobrosAnulacionGrabar();
                    }).button( "disable" );

        <?php
        reset($arrAjuste);
        $i = 1;
        while ($arrTMP = each($arrAjuste)) {
            ?>
                        intCorrelativo = <?php print $i; ?>;
                        drawNewLine(intCorrelativo, "<?php print $arrTMP["value"]["codigo"]; ?>", "<?php print $arrTMP["value"]["nombre"]; ?>", "<?php print $arrTMP["value"]["tipo"]; ?>", "<?php print $arrTMP["value"]["monto"]; ?>" );
            <?php
            $i++;
        }
        ?>
                intCorrelativo = <?php print $i; ?>;
                drawNewLine(intCorrelativo);
                                    
            });
            </script>
        </div>
        <?php
    } else {
        echo "Error no hay cargo contable generado!";
    }
}

function fntAcademicoCobrosAnulacionGrabar($db) {
    $empresa = 1;
    $valor = getParam("hdnAcademicoCobrosAnulacionValor");
    $arrfecha = explode("-", getParam("hdnAcademicoCobrosAnulacionFecha"));
    $fecha = $arrfecha[2] . "-" . $arrfecha[1] . "-" . $arrfecha[0];
    $concepto = getParam("hdnAcademicoCobrosAnulacionConcepto");
    $strNotas = "";
    $datosCuenta = explode("_", getParam("hdnFkCtaCorriente"));

    $strQuery = "SELECT * 
                 FROM   cllg_contab_ciclo 
                 WHERE  activo = '1' 
                 AND    fecha_inicio <= '{$fecha}' 
                 AND    fecha_fin >= '{$fecha}'
                 AND    total_activo > 0 
                 AND    total_pasivo > 0
                 AND    fk_empresa = '{$empresa}'";
    $qTMP = $db->query($strQuery);
    $intCicloCerrado = $db->num_rows;
    $db->free_result($qTMP);

    $strQuery = "SELECT * 
                 FROM   cllg_contab_ciclo 
                 WHERE  activo = '1' 
                 AND    fecha_inicio <= '{$fecha}' 
                 AND    fecha_fin >= '{$fecha}'
                 AND    fk_empresa = '{$empresa}'";
    $qTMP = $db->query($strQuery);
    $intCicloCorrecto = $db->num_rows;
    $db->free_result($qTMP);

    if ($intCicloCerrado > 0) {
        ?>
        <div class="ui-widget" style="border: 0px solid white; width: 900px; height: auto; vertical-align: bottom;" align="center">
            <div class="ui-state-error ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 450px;"> 
                <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span>
                    No se puede ingresar partida en una fecha ya cerrada.</p>
            </div>
        </div>
        <br>
        <?php
    } else if ($intCicloCorrecto == 0) {
        ?>
        <div class="ui-widget" style="border: 0px solid white; width: 900px; height: auto; vertical-align: bottom;" align="center">
            <div class="ui-state-error ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 450px;"> 
                <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: 0.3em;"></span>
                    La fecha de la partida no esta configurada.</p>
            </div>
        </div>
        <br>
        <?php
    } else {
        $strQuery = "SELECT * FROM cllg_contab_ciclo WHERE activo = '1' AND fk_empresa = '{$empresa}'";
        $qTMP = $db->query($strQuery);
        $intNumRows = $db->num_rows;
        $rTMP = $db->fetch_array($qTMP);
        $intCiclo = $rTMP["codigo"];
        $db->free_result($qTMP);
        if ($intNumRows > 0) {
            $strQuery = "INSERT INTO cllg_contab_ajuste 
                         (id, fecha, monto, ciclo, descripcion)
                         VALUES
                         (NULL, '{$fecha}', {$valor}, '{$intCiclo}', '{$concepto}')";
            $db->query($strQuery);
            $intAjuste = mysql_insert_id($db->link_id);

            if ($intAjuste > 0) {
                while ($arrPost = each($_POST)) {
                    $arrExplode = explode("_", $arrPost["key"]);
                    if ($arrExplode[0] == "hdnCuenta" && $arrPost["value"] > 0) {

                        $debe = getParam("txtDebe_" . $arrExplode[1]);
                        $haber = getParam("txtHaber_" . $arrExplode[1]);
                        if ($debe > 0 && $haber == 0) {
                            $monto = $debe;
                            $debe = 1;
                            $haber = 0;
                        } else if ($debe == 0 && $haber > 0) {
                            $monto = $haber;
                            $debe = 0;
                            $haber = 1;
                        }
                        $strQuery = "INSERT INTO cllg_contab_cuenta_ajuste 
                                     (cuenta, debe, haber, monto, ajuste)
                                     VALUES
                                     ('{$arrPost["value"]}', '{$debe}', '{$haber}', '{$monto}', '{$intAjuste}')";
                        $db->query($strQuery);
                    }
                }
                reset($_POST);
                while ($arrTMP = each($_POST)) {
                    $arrExplode = explode("_", $arrTMP["key"]);
                    if ($arrExplode[0] == "sltCuenta") {
                        $intCuenta = ( isset($_POST["sltCuenta_{$arrExplode[1]}_{$arrExplode[2]}"]) ) ? $_POST["sltCuenta_{$arrExplode[1]}_{$arrExplode[2]}"] : 0;
                        $sinMonto = ( isset($_POST["hdnMonto_{$arrExplode[1]}_{$arrExplode[2]}"]) ) ? mround($_POST["hdnMonto_{$arrExplode[1]}_{$arrExplode[2]}"], 2) : 0;

                        $db->query("INSERT INTO cllg_bnc_docto_solicitud 
                                        (FECHA, MONTO, TIPO, NOMBRE, CONCEPTO, ESTADO, FK_CUENTA, MODULO) 
                                    VALUES 
                                        ('{$fecha}', '{$sinMonto}', '3', '', '{$concepto}', '4', '{$intCuenta}', 'ACADEMICO')");
                        $intSolicitud = mysql_insert_id($db->link_id);
                        $intNota = fntAcademicoCobrosAnulacionSiguienteNota($db, "2");
                        $strNotas .= (empty($strNotas)) ? "" : ", ";
                        $strNotas .= $intNota;
                        $db->query("INSERT INTO cllg_bnc_notas (FK_CUENTA, TIPO, ID, MONTO, FECHA, CONCEPTO, ESTADO, FK_SOLICITUD, FK_AJUSTE) 
                                    VALUES ('{$intCuenta}', '2', '{$intNota}', '{$sinMonto}', '{$fecha}', '{$concepto}', '1', '{$intSolicitud}', '{$intAjuste}')");
                        $db->query("UPDATE cllg_academico_pagos_detail SET FK_AJUSTE_ANULACION = '{$intAjuste}', 
                        ESTADO='ANULADO',
                        FK_ND_ANULACION = '{$intNota}' WHERE ID = '{$arrExplode[2]}'");

                        //modifica el saldo del cobro
                        modificarSaldoCobro($arrExplode[1], $sinMonto, 2, $db);

                        //actualiza el estado de cuenta 
                        $fkBenefactor = $datosCuenta[1] == "BENEFACTOR" ? $datosCuenta[0] : "0";
                        $fkEstudiante = $fkBenefactor == "0" ? $datosCuenta[0] : "0";
                        registerMovCta(array("cobro" => $arrExplode[1], "fkEstudiante" => $fkEstudiante,
                            "fkBenefactor" => $fkBenefactor, "value" => $sinMonto,
                            "debe" => 0, "haber" => $sinMonto,
                            "DESCRIPCION" => "Anulacion de Pago: " . $arrExplode[2]), $db);
                    }
                }
                ?>
                <div class="ui-widget" style="border: 0px solid white; width: 900px; height: auto; vertical-align: bottom;" align="center">
                    <div class="ui-state-highlight ui-corner-all" style="margin-top: 0px; padding: 0pt 0.7em; height: auto; width: 320px;"> 
                        <p><span class="ui-icon ui-icon-info" style="float: left; margin-right: 0.3em;"></span>
                            Partida ingresada No. <?php print $intAjuste; ?><br>
                            Notas de debito ingresadas No. <?php print $strNotas; ?></p>
                    </div>
                </div>
                <?php
            }
        }
    }
}

function fntAcademicoCobrosAnulacionSiguienteNota($db, $intTipo) {
    $intNota = 0;
    $strQuery = "SELECT  MAX(ID) AS ID 
                FROM    cllg_bnc_notas
                WHERE   cllg_bnc_notas.TIPO = '{$intTipo}'";
    $qTMP = $db->query($strQuery);
    while ($rTMP = $db->fetch_array($qTMP)) {
        $intNota = $rTMP["ID"] + 1;
    }
    $db->free_result($qTMP);

    return $intNota;
}

function mround($number, $precision = 0) {

    $precision = ($precision == 0 ? 1 : $precision);
    $pow = pow(10, $precision);

    $ceil = ceil($number * $pow) / $pow;
    $floor = floor($number * $pow) / $pow;

    $pow = pow(10, $precision + 1);

    $diffCeil = $pow * ($ceil - $number);
    $diffFloor = $pow * ($number - $floor) + ($number < 0 ? -1 : 1);

    if ($diffCeil >= $diffFloor)
        return $floor;
    else
        return $ceil;
}
?>